package com.rong.juc_test.juc_base.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 1; i <= 5; i++){
            final  int tempInt = i;
            new Thread(() -> {
                myCache.put(tempInt+ "",tempInt+"");
            },String.valueOf(i)).start();
        }

        try {
            TimeUnit.MICROSECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 1; i <= 5; i++){
            final  int tempInt = i;
            new Thread(() -> {
                myCache.get(tempInt+ "");

            },String.valueOf(i)).start();
        }
    }
}

// 资源类
class MyCache{
    // 创建map 不断放入 取出数据  volatile防止指令重排序
    private volatile Map<String,String> map = new HashMap<>();
    // 创建读写锁
    ReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();


    // 放数据 写锁：写锁只能有一个线程获得
    public void put(String key,String value) {
        reentrantReadWriteLock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"\t 正在写入:"+key);
        try {
            map.put(key,value);
            TimeUnit.MICROSECONDS.sleep(300);
            System.out.println(Thread.currentThread().getName()+"\t 写入完成" + key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
    }
    // 取数据 读锁：允许多个线程同时获得
    public  Object get(String key) {
        reentrantReadWriteLock.readLock().lock();
        Object val = null;
        try {
            System.out.println(Thread.currentThread().getName()+"\t 正在读取:"+key);
            TimeUnit.MICROSECONDS.sleep(300);
            val = map.get(key);
            System.out.println(Thread.currentThread().getName()+"\t 读取完成:"+key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            reentrantReadWriteLock.readLock()
            .unlock();
        }
        return val;
    }


}